package com.example.springcloud.feign.server.controller;

import com.example.springcloud.feign.api.UserApi;
import com.example.springcloud.feign.api.dto.UserDTO;
import com.example.springcloud.rpc.api.PageRequest;
import com.example.springcloud.rpc.api.PageResponse;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.IntStream;

/**
 * @author fanhang
 */
@RestController
public class UserController implements UserApi {
    private final List<UserDTO> dataList = IntStream.range(1, 95).mapToObj(UserController::createUser).toList();

    private static UserDTO createUser(long i) {
        UserDTO user = new UserDTO();
        user.setId(i);
        user.setName("name-" + i);
        int age = (int) (i % 10);
        user.setAge(20 + age);
        return user;
    }

    @Override
    public String hello(String name) {
        return "hello: " + name;
    }

    @Override
    public UserDTO getUser(Long id) {
        return createUser(id);
    }

    @Override
    public PageResponse<UserDTO> getUserList(PageRequest page) {
        int startIndex = page.getPageNum() * page.getPageSize();
        List<UserDTO> list = dataList.stream().skip(startIndex).limit(page.getPageSize()).toList();
        int pages = dataList.size() / page.getPageSize();
        if (dataList.size() % page.getPageSize() != 0) {
            pages = pages + 1;
        }
        return new PageResponse<>(page.getPageNum(), page.getPageSize(), 100, pages, list);
    }
}
